package admininterceptor

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-playground/validator"
	"strconv"
	"time"
	"vpn-management-server/logger"
	"vpn-management-server/network"
	"vpn-management-server/security/code"
	"vpn-management-server/src/model/adminlogmodel"
	"vpn-management-server/src/model/adminmodel"
	"vpn-management-server/src/service/adminlogservice"
	"vpn-management-server/src/service/adminservice"
)

func AdminValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	// TODO 解析管理员用户数据Json
	var admin adminmodel.Admin
	err := json.Unmarshal([]byte(request.Parameters), &admin)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	// TODO 验证json字段的合法性
	valid := validator.New()
	err = valid.Struct(admin)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	// TODO 验证管理员权限的合法性
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == adminmodel.SuperAdmin {
		request.SetModel(&admin)
		return true
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}

func AdminNameInfoValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	var adminNameInfo adminmodel.AdminNameInfo
	err := json.Unmarshal([]byte(request.Parameters), &adminNameInfo)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	valid := validator.New()
	err = valid.Struct(adminNameInfo)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	// TODO 验证管理员权限的合法性 只有超级管理员才能够执行该操作
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == adminmodel.SuperAdmin {
		request.SetModel(&adminNameInfo)
		return true
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}

func AdminRankValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	// TODO 验证管理员权限等级
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == 0 {
		return true
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}

func UGroupAdminValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	var UGroupAdmin adminmodel.UGroupAdmin
	// TODO json-->ugroupAdminJson
	err := json.Unmarshal([]byte(request.Parameters), &UGroupAdmin)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	// TODO 验证参数的合法性
	valid := validator.New()
	err = valid.Struct(&UGroupAdmin)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	// TODO 验证管理员权限的合法性 只有超级管理员和系统管理员可以创建用户组管理员
	if rank := adminservice.GetAdminRankService(ctx, request, response); rank == adminmodel.SuperAdmin || rank == adminmodel.SystemAdmin {
		request.SetModel(&UGroupAdmin)
		return true
	} else {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "have no authority")
		response.Code = code.UNAUTHORIZED
		response.ErrorMsg = "have no authority"
		return false
	}
}

func AdminLoginValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	var AdminLogin adminmodel.AdminLogin
	// TODO json-->AdminLoginJson
	err := json.Unmarshal([]byte(request.Parameters), &AdminLogin)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	// TODO 验证参数的合法性
	valid := validator.New()
	err = valid.Struct(&AdminLogin)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	// TODO 还需要加入验证密码是否过期
	request.SetModel(&AdminLogin)
	return true
}

func AdminResetValidator(ctx context.Context, request *network.NetRequest, response *network.NetResponse) bool {
	var AdminReset adminmodel.AdminReset
	// TODO json-->AdminResetJson
	err := json.Unmarshal([]byte(request.Parameters), &AdminReset)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "UnMarshal Parameters to adminJson error,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "parse parameters fail"
		return false
	}
	// TODO 验证参数的合法性
	valid := validator.New()
	err = valid.Struct(&AdminReset)
	if err != nil {
		logger.Logger.ErrorWithConn(ctx.Value("conn_id").(string), "validate Parameters fail,", err)
		response.Code = code.BAD_REQUEST
		response.ErrorMsg = "validate parameters fail"
		return false
	}
	// 修改密码任何管理员都可以
	request.SetModel(&AdminReset)
	return true
}

func AddAdminLogToChan(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	if admin, ok := request.GetModel().(*adminmodel.Admin); ok {
		adminlogservice.AddAdminLogToChan(adminlogservice.ChanAdminLogs, adminlogmodel.AdminLog{
			Name:      adminservice.GetCurrAdminService(ctx, request, response).Name,
			Source:    request.GetRemote(),
			Location:  "地址",
			Behavior:  "添加管理员：" + admin.Name,
			TimeStamp: strconv.FormatInt(time.Now().Unix(), 10),
		})
	}
}

func DeleteAdminLogToChan(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	if adminNameInfo, ok := request.GetModel().(*adminmodel.AdminNameInfo); ok {
		adminlogservice.AddAdminLogToChan(adminlogservice.ChanAdminLogs, adminlogmodel.AdminLog{
			Name:      adminservice.GetCurrAdminService(ctx, request, response).Name,
			Source:    request.GetRemote(),
			Location:  "地址",
			Behavior:  "删除管理员：" + adminNameInfo.Name,
			TimeStamp: strconv.FormatInt(time.Now().Unix(), 10),
		})
	}
}

func AddUGroupAdminLogToChan(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	if UGroupAdmin, ok := request.GetModel().(*adminmodel.UGroupAdmin); ok {
		adminlogservice.AddAdminLogToChan(adminlogservice.ChanAdminLogs, adminlogmodel.AdminLog{
			Name:      adminservice.GetCurrAdminService(ctx, request, response).Name,
			Source:    request.GetRemote(),
			Location:  "地址",
			Behavior:  "添加用户组管理员：" + UGroupAdmin.Name,
			TimeStamp: strconv.FormatInt(time.Now().Unix(), 10),
		})
	}
}

func ResetAdminLogToChan(ctx context.Context, request *network.NetRequest, response *network.NetResponse) {
	if adminReset, ok := request.GetModel().(*adminmodel.AdminReset); ok {
		adminlogservice.AddAdminLogToChan(adminlogservice.ChanAdminLogs, adminlogmodel.AdminLog{
			Name:      adminservice.GetCurrAdminService(ctx, request, response).Name,
			Source:    request.GetRemote(),
			Location:  "地址",
			Behavior:  fmt.Sprintf("修改管理员%s的密码", adminReset.Name),
			TimeStamp: strconv.FormatInt(time.Now().Unix(), 10),
		})
	}
}
